package auth

//用户注册模块
import (
	"beluga/models"
	"beluga/tools"
	"fmt"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

//Register 注册控制器
type Register struct {
	beego.Controller
}

//User 用户信息控制器
type User struct {
	UserName   string `orm:"unique;size(32)" form:"username"  valid:"Required;MaxSize(20);MinSize(6)"`
	Password   string `orm:"size(128)" form:"password" valid:"Required;MaxSize(20);MinSize(6)"`
	RePassword string `orm:"-" form:"repassword" valid:"Required"`
	FirstName  string `orm:"unique;size(32)" form:"first_name"  valid:"Required;MaxSize(20);MinSize(1)"`
	LastName   string `orm:"unique;size(32)" form:"last_name"  valid:"Required;MaxSize(20);MinSize(6)"`
	IsActive   bool   `orm:"type(bool)"`
}

//RequestCode 返回码规范
type RequestCode struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

//Post post
func (c *Register) Post() {
	//var objectid = "ojbk"
	o := orm.NewOrm()
	o.Using("default")
	username := c.GetString("username")
	firstName := c.GetString("firstname")
	lastName := c.GetString("lastname")
	password := c.GetString("password")
	repassword := c.GetString("repassword")
	reg := new(models.User)
	//fmt.Println(firstName)
	reg.UserName = username
	reg.FirstName = firstName
	reg.LastName = lastName
	reg.Password, _ = tools.PasswordEncode(password, "", 0)
	reg.IsActive = true
	//id, err := o.Insert(reg)
	//检查是否重复注册
	check := models.User{UserName: username}
	err := o.Read(&check, "UserName")
	rc := RequestCode{}
	if password != repassword {
		rc.Code = 3
		rc.Msg = "两次输入的密码不一样"
	} else if err == orm.ErrNoRows {
		//查询结果为空， 写入数据
		id, err := o.Insert(reg)
		if err == nil {
			fmt.Println(id)
		}
		rc.Code = 0
		rc.Msg = "注册成功"
	} else if err == orm.ErrMissPK {
		rc.Code = 1
		rc.Msg = "找不到 pk"
	} else {
		rc.Code = 2
		rc.Msg = "用户已存在，请勿重复注册"

	}
	c.Data["json"] = rc
	c.ServeJSON()
}

//Get 请求处理
func (c *Register) Get() {
	c.Data["pageName"] = "用户注册"
	//c.Ctx.SetCookie("general", "name", 36000, "/auth/register")
	c.TplName = "auth/register.tpl"
}
